

import json_util

try:
    from top.starp.util import m
    from top.starp.util import common
    from top.starp.util import k
except Exception as e:
    print(e)
    import m
    import common
    import k

from typing import List
from pymongo.collection import Collection
from pymongo.database import Database
from pymongo import ASCENDING, MongoClient
from pymongo.errors import PyMongoError
from bson import ObjectId
from bson.son import SON
from bson.json_util import dumps
from bson.code import Code

# do_mongo=False
do_mongo=True
# D:\proj\python\st-util\top\starp\util\mongo_util.py
no_mongo_open_tip=rf"没有开启do_mongo 请在top\starp\util\mongo_util.py 中设置 do_mongo=True"

def greaterThan(key,val):
    return {
        m.match: {
            m.expr: {m.gt : [ {m.toDouble : f"${key}" }, val ] }
        }
    }


def find_newest(collection,limit=10,sort_by="_id"):
    if not do_mongo:
        # print("mongo 没有开启 do_mongo")
        print(no_mongo_open_tip)
        return
    # 查询最新的10条记录
    results = collection.find().sort(sort_by, -1).limit(limit)
    return results

def mongo_join(local_doc: str, other_doc: str, local_field: str,
               foreign_field: str, mongo_db: Database,
               projection_operation: object = None) -> List[dict]:
    join_doc = 'joinDoc'
    lookup_operation = {
        '$lookup': {
            'from': other_doc,
            'localField': local_field,
            'foreignField': foreign_field,
            'as': join_doc
        }
    }
    criteria = {join_doc: {'$ne': []}}
    if projection_operation is None:
        pipeline = [
            lookup_operation,
            {'$match': criteria}
        ]
    else:
        pipeline = [
            lookup_operation,
            projection_operation,
            {'$match': criteria}
        ]

    local_collection: Collection = mongo_db[local_doc]
    result = local_collection.aggregate(pipeline)
    return list(result)

def conf_path_to_mongodb_url(conf_path):
  mongodbJobDetail_conf=json_util.file_path_to_dict(conf_path)
  # {mongodbJobDetail_conf['db_name']}
  db_name= mongodbJobDetail_conf.get('db_name')
  if db_name is None:
      db_name=""
  url=rf"mongodb://{mongodbJobDetail_conf['username']}:{mongodbJobDetail_conf['password']}@{mongodbJobDetail_conf['host']}:27017/{db_name}?authSource=admin&readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false"
  return url

def get_connection(conf_str):
    connect = MongoClient(conf_str)    
    return connect


def getConnectionByConfPath(conf_path):
    conf=conf_path_to_mongodb_url(conf_path)
    client=get_connection(conf)
    return client

def list_all(collection):
    if not do_mongo:
        # print("mongo 没有开启 do_mongo")
        print(no_mongo_open_tip)
        return
    collection_find=collection.find()
    collection_find=list(collection_find)
    # print("collection_find")
    # print(collection_find)
    return collection_find


def like(word='大纲'):
    doc_name_regex = f'.*{word}.*'
    return {'$regex': doc_name_regex}

def insert_data_do(data,collection):
    if not do_mongo:
        # print("mongo 没有开启 do_mongo")
        print(no_mongo_open_tip)
        return
    if  type(data)==list:
        if len(data)==0:
            return
        collection.insert_many(data)
    else:
        collection.insert_one(data)


def insert_data(data,collection):
    if not do_mongo:
        # print("mongo 没有开启 do_mongo")
        print(no_mongo_open_tip)
        return
    # insert_data_do(data,collection)
    try:
        insert_data_do(data,collection)
    except Exception as e:
        print(e)
        # print(da )
        if  type(data)==list:
            print("data[:2]")
            print(data[:2])
            print("len(data)",len(data))
        else:
            print("data")
            print(data)
        print("insert_data_do(data,collection) error")
        raise e

    
    # if  type(data)==list:
    #     if len(data)==0:
    #         return
    #     collection.insert_many(data)
    # else:
    #     collection.insert_one(data)
"""
{
  "username": "root",
  "password": ".",
  "host":"10...",
  "db_name":""
}

"""
# mongodbJobDetail_conf['username']
# D:\home\app\private-conf\mongodbJobDetail.json

# conn=getConnectionByConfPath(conf_path=common.mongodb_conf_path_starp)
# db=conn[k.use_log]

if __name__=="__main__":
    # list_all(collection)
    pass